<template>
  <div class="top">
    <router-link to="/personrecom">
      <img src="@/assets/网易云音乐.png">
    </router-link>
    <div class="btn">
      <button class="btn-left"
              @click="back"><i class="el-icon-arrow-left"></i></button>
      <button class="btn-right"
              @click="forward"><i class="el-icon-arrow-right"></i></button>
    </div>
    <div class="search">
      <el-input v-model="keywords"
                placeholder="陈奕迅"
                @blur="showInfoTip = false"
                @focus="hotsearch"
                @keyup.enter.native="goSearch(keywords)"
                prefix-icon="el-icon-search"
                clearable></el-input>
      <transition name="el-fade-in">
        <div class="search-info_tip"
             v-show="showInfoTip">
          <div class="first"
               v-show="keywords ===''">
            <div class="search-history"
                 style="margin:10px;margin-bottom: 0;">
              <div class="history">搜索历史
                <svg class="icon"
                     aria-hidden="true"
                     style="float:right;width:15px;height:15px;margin-top: 2px;"
                     @click="delHistory">
                  <use xlink:href="#icon-shanchu"></use>
                </svg>
              </div>
              <span class="h-text"
                    v-for="item in KeywordList"
                    :key="item"
                    @click="searchHistory(item)">{{ item }}</span>
            </div>
            <div class="hot-search">
              <p style="font-size:14px;margin-left: 8px;">热搜榜</p>
              <div class="hot-content">
                <div v-for="(item,index) in  hotSearchList"
                     :key='item.id'
                     @click="searchHistory(item.searchWord)"
                     class="hot-li">
                  <span class="hot-index">{{ index +1}}</span>
                  <span class="hot-name">{{ item.searchWord}}</span>
                  <span class="hot-name"
                        style="color:#666;opacity: 0.4;font-size: 11px;margin-left: 5px;">{{ item.score }}</span>
                  <img :src=" item.iconUrl "
                       v-if="item.iconUrl"
                       class="tp">
                  <p class="j-s"
                     v-if="item.content">{{ item.content }}</p>
                </div>
              </div>
            </div>
          </div>
          <div class="two"
               v-show="keywords !==''">
            <p>搜"{{ keywords }}"相关的内容<i class="el-icon-arrow-right"></i></p>
            <div class="single ">
              <p class="common"><svg class="icon"
                     aria-hidden="true">
                  <use xlink:href="#icon-yinle"></use>
                </svg>&#12288;单曲</p>
              <ul class="s-two">
                <li v-for="(item,index) in searchSuggest.songs"
                    :key="index"
                    @click="searchHistory(item.name)">{{ item.name }}-{{ item.artists[0].name }}</li>
              </ul>
            </div>
            <div class="album ">
              <p class="common"><svg class="icon"
                     aria-hidden="true">
                  <use xlink:href="#icon-zhuanji"></use>
                </svg>&#12288;专辑</p>
              <ul class="s-two">
                <li v-for="(al) in searchSuggest.albums"
                    :key="al.id"
                    @click="toAlbumDetail(al.id)">{{ al.name }}-{{ al.artist.name  }}</li>
              </ul>
            </div>
            <div class="singer">
              <p class="common"><svg class="icon"
                     aria-hidden="true">
                  <use xlink:href="#icon-gedan"></use>
                </svg>&#12288;歌手</p>
              <ul class="s-two">
                <li v-for="(ar) in searchSuggest.artists"
                    :key="ar.id"
                    @click="toArtistDetail(ar.id)">{{ ar.name }}</li>
              </ul>
            </div>
            <div class="songList">
              <p class="common"><svg class="icon"
                     aria-hidden="true">
                  <use xlink:href="#icon-yonghu"></use>
                </svg>&#12288;歌单</p>
              <ul class="s-two">
                <li v-for="(p) in searchSuggest.playlists"
                    :key="p.id"
                    @click="toPlayListDetail(p.id)">{{ p.name }}</li>
              </ul>
            </div>
          </div>
        </div>
      </transition>
    </div>
    <div class="user">
      <img src="@/assets/我的.png"
           @click="Show"
           class="us-er"
           v-if="isLogin ===false">
      <img :src="getAcount.avatarUrl"
           @click="Show"
           v-else>
    </div>
    <span v-if="isLogin===true"
          @click=" Loginout">{{ getAcount.nickname}}</span>
    <Login v-if="isShow"></Login>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import { hotsearch, getSuggest } from '@/api/search'
import Login from '@/pages/Login'
export default {
  name: 'Header',
  components: { Login },
  props: ['changeShow'],
  data () {
    return {
      isShow: false,
      keywords: '',//关键字
      showInfoTip: false,
      KeywordList: [],//搜索历史
      hotSearchList: [],//热搜列表
      searchSuggest: {},//搜索建议
      getAcount: {},
      KeyWord: ''
    }
  },
  mounted () {
    //历史记录显示
    this.KeywordList = JSON.parse(localStorage.getItem('KeywordList')) ? JSON.parse(localStorage.getItem('KeywordList')) : []
  },
  computed: {
    ...mapState({
      isLogin: (state) => {
        return state.user.isLogin
      },
    })
  },
  methods: {
    ...mapMutations(['UPDATEDISLOGIN']),
    // 后退按钮
    back () {
      this.$router.back()
    },
    // 前进按钮
    forward () {
      this.$router.forward()
    },
    // 登录框显示
    Show () {
      if (this.isLogin == false) {
        this.isShow = true
      } else {
        this.$router.push('/personal')
      }
    },
    // 退出登录
    Loginout () {
      this.$store.dispatch('getLogout')
    },
    // 去搜索
    async goSearch (item) {
      if (this.keywords !== '') {
        this.KeywordList.unshift(this.keywords)
        //去重
        this.KeywordList = [...new Set(this.KeywordList)]
        //固定长度
        if (this.KeywordList.length > 5) {
          this.KeywordList.splice(this.KeywordList.length - 1, 1)
        }
        //历史搜索存进浏览器
        localStorage.setItem('KeywordList', JSON.stringify(this.KeywordList))
        // 跳转搜索
        this.$router.push({ path: '/search', query: { keywords: item } })
        this.keywords = ''
      }
    },
    // 热搜列表
    async hotsearch () {
      this.showInfoTip = true
      let res = await hotsearch()
      if (res.code === 200) {
        this.hotSearchList = res.data
      }
    },
    // 点击历史记录或者列表li进行搜索
    async searchHistory (item) {
      this.KeyWord = item
      this.$router.push({ path: '/search', query: { keywords: this.KeyWord } })
      this.keywords = ''
    },
    // 删除按钮
    delHistory () {
      this.$confirm('确认清空历史记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        localStorage.removeItem("KeywordList")
        this.KeywordList = []
      }).catch(() => {

      }) // 添加错误捕获

    },
    // 搜索建议
    async getSuggest (keywords) {
      let res = await getSuggest({ keywords: keywords })
      this.searchSuggest = res.result
    },
    //去专辑页
    toAlbumDetail (id) {
      this.keywords = ''
      if (typeof id === 'number') {
        this.$router.push({ path: '/albumdetail', query: { id: id } })
      }
    },
    //去歌手页
    toArtistDetail (id) {
      this.keywords = ''
      if (typeof id === 'number') {
        this.$router.push({ path: '/homeitem/:id', query: { id: id } })
      }
    },
    //去歌单页
    toPlayListDetail (id) {
      this.keywords = ''
      if (typeof id === 'number') {
        this.$router.push({ path: '/homeitem/:id', query: { id: id } })
      }
    },
    // 判断是否登录
    Login () {
      if (this.isLogin !== false) {
        this.getAcount = JSON.parse(localStorage.getItem('getAcount'))
      } else {
        return
      }
    }
  },
  watch: {
    keywords () {//如果关键字不为空则触发函数
      if (this.keywords !== '') {
        this.getSuggest(this.keywords)
      }
    },
    isLogin: {
      immediate: true,
      // 当islogin发生改变时。调用handler函数
      handler () {
        if (JSON.parse(window.localStorage.getItem('isLogin')) == true) {
          this.getAcount = JSON.parse(window.localStorage.getItem('getAcount'))
          this.$store.commit('UPDATEDISLOGIN', true)
        }
      }
    },
    KeyWord () {//监测关键字是否改变，是则发起全局事件‘KeyWord’
      this.$bus.$emit('keyword', this.KeyWord)
    }
  }
}
</script>

<style scoped lang="less">
.top {
  display: flex;
  align-items: center;
  width: 1536px;
  height: 60px;
  background-color: #ec4141;
  img {
    display: flex;
    margin-left: 10px;
    height: 50px;
  }
  .btn {
    margin-top: -4px;
    display: flex;
    margin-left: 100px;
    button {
      display: flex;
      height: 26px;
      width: 26px;
      outline: 0;
      border: 0;
      background-color: #e13e3e;
      color: #ffffff;
      justify-content: center;
      align-items: center;
      border-radius: 50%;
      margin-right: 10px;
      // 鼠标变小手
      cursor: pointer;
    }
  }
  .search {
    float: left;
    width: 200px;
    position: relative;
    z-index: 2000;
    /deep/.el-input__icon {
      margin-top: -2px;
    }
    /deep/.el-input__inner {
      width: 200px;
      height: 35px;
      border-radius: 20px;
      outline: none;

      background-color: #e33e3e;
      overflow: hidden;
      // 背景位置
      background-position: 10px 5px;
      border: 1px double #e33e3e;
      // 改变输入框光标颜色
      caret-color: #fff;
      color: #fff;
    }
    /* 搜索建议等的弹出层 */
    .search-info_tip {
      position: absolute;
      top: 50px;
      left: 0;
      width: 340px;
      min-height: 340px;
      max-height: 420px;
      transition: all 0.5s;
      overflow: auto;
      border-radius: 8px;
      box-shadow: 0 1px 4px #dddddd;
      background-color: #fff;
      z-index: 100;
      font-weight: lighter;
      color: #666;
      /*滚动条高宽度*/
      &::-webkit-scrollbar {
        width: 8px;
        height: 4px;
      }
      /*滚动条滑块*/
      &::-webkit-scrollbar-thumb {
        border-radius: 3px;
        box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
        background: #f6f4f4;
      }
      .first {
        .history {
          height: 20px;
          width: 85px;
          line-height: 20px;
          margin-bottom: 5px;
          margin-left: 8px;
        }
        .h-text {
          cursor: pointer;
          padding: 5px 10px;
          margin-top: 5px;
          margin-right: 10px;
          height: auto;
          color: #000;
          font-size: 13px;
          width: auto;
          border: 1px solid rgb(119, 110, 110);
          border-radius: 15px;
          display: inline-block;
        }
        .hot-search {
          margin: 10px;
          margin-bottom: 0;
          .hot-content {
            height: auto;
            .hot-li {
              margin: 10px 0 0px 5px;
              max-height: 60px;
              cursor: pointer;
              &:nth-child(1) {
                .hot-index {
                  color: #e13e3e;
                }
                .hot-name {
                  font-weight: 550;
                }
              }
              &:nth-child(2) {
                .hot-index {
                  color: #e13e3e;
                }
                .hot-name {
                  font-weight: 550;
                }
              }
              &:nth-child(3) {
                .hot-index {
                  color: #e13e3e;
                }
                .hot-name {
                  font-weight: 550;
                }
              }
              .hot-index {
                width: 20px;
                height: 20px;
                margin-left: -5px;
                text-align: center;
                line-height: 20px;
                color: #000;
              }
              .hot-name {
                display: inline-block;
                margin: 0;
                padding: 0;
                width: auto;
                height: 20px;
                margin-left: 10px;
                font-size: 13px;
                line-height: 20px;
                color: #000;
              }
              .tp {
                width: 15px;
                height: 15px;
                float: right;
              }
              .j-s {
                margin-left: 25px;
                font-size: 12px;
              }
            }
          }
        }
      }
      .two {
        p {
          padding: 5px;
          font-size: 13px;
          &:hover {
            color: #000;
          }
        }
        .s-two {
          li {
            font-size: 12px;
            padding: 5px;
            margin-bottom: 5px;
            padding-left: 44px;
            color: #000;
            &:hover {
              background-color: rgb(244, 243, 243);
              cursor: pointer;
            }
          }
        }
        .common {
          color: #bfbfbf;
          margin-left: 10px;
          margin-top: -8px;
        }
      }
    }
  }
  .user {
    .us-er {
      display: flex;
      margin-left: 15px;
      width: 25px;
      height: 25px;
    }
    img {
      display: flex;
      margin-left: 15px;
      width: 25px;
      height: 25px;
      border-radius: 15px;
    }
  }
  span {
    cursor: pointer;
    display: inline-block;
    width: 100px;
    height: 25px;
    padding: 5px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-left: 5px;
    color: rgb(252, 251, 251);
    font-size: 14px;
  }
}
</style>